import axios from 'axios'
import { ElLoading } from 'element-plus'
import router from '../router/index'

const service = axios.create({
  // process.env.NODE_ENV === 'development' 来判断是否开发环境
  // easy-mock服务挂了，暂时不使用了
  // baseURL: "47.110.252.120",
  baseURL: 'https://boshi.channce.com/boshi',
  timeout: 50000000,
  crossDomain: true,
  withCredentials: true,
})

let loading
let loadingNum = 0

//请求加载
function startLoading() {
  if (loadingNum == 0) {
    loading = ElLoading.service({
      lock: false,
      text: '加载中...',
      background: 'rgba(255,255,255,0.5)',
    })
  }
  //请求数量加1
  loadingNum++
}
//请求加载结束
function endLoading() {
  //请求数量减1
  loadingNum--
  if (loadingNum <= 0) {
    loading.close()
  }
}

service.interceptors.request.use(
  (config) => {
    console.log(config)
    startLoading()
    if (sessionStorage.getItem('Token')) {
      config.headers['wt'] = sessionStorage.getItem('Token')
    }
    return config
  },
  (error) => {
    console.log(error)
    return Promise.reject()
  }
)

service.interceptors.response.use(
  (response) => {
    endLoading()
    if (response.status === 200) {
      if (response.data.code == 50014 || response.data.code == 50013 || response.data.code == 4000) {
        // 清除登录
        sessionStorage.clear()
        router.replace({
          path: '/login',
          query: {
            redirect: router.currentRoute.fullPath,
          },
        })
      }
      return response.data
    } else {
      Promise.reject()
    }
  },
  (error) => {
    if (error.response) {
      switch (error.response.code) {
        case 50014:
      }
    }
    return Promise.reject()
  }
)

export default service
